﻿using Fast;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

namespace Microsoft.AspNetCore.Builder
{
    /// <summary>
    /// 使用Fast框架扩展类
    /// </summary>
    public static class FastApplicationBuilderExtensions
    {
        /// <summary>
        /// 注入基础中间件（带Swagger）
        /// </summary>
        /// <param name="app"></param>
        /// <returns></returns>
        public static IApplicationBuilder UseFast(this IApplicationBuilder app)
        {
            Check.NotNull(app, nameof(app));

            ConfigureApp(app);

            app.UseSwaggerDocument();

            InitializeApplication(app);
            return app;
        }

        /// <summary>
        /// 初始化应用
        /// </summary>
        /// <param name="app"></param>
        private static void InitializeApplication(IApplicationBuilder app)
        {
            var application = app.ApplicationServices.GetRequiredService<IFastApplication>();
            var applicationLifetime = app.ApplicationServices.GetRequiredService<IHostApplicationLifetime>();

            applicationLifetime.ApplicationStopping.Register(() =>
            {
                application.Shutdown();
            });

            applicationLifetime.ApplicationStopped.Register(() =>
            {
                application.Dispose();
            });

            application.Initialize(app.ApplicationServices);
        }

        private static void ConfigureApp(IApplicationBuilder app)
        {
            //获取并储存应用程序的服务容器
            App.ServicesProvider = app.ApplicationServices;
        }
    }
}
